package com.alipan.service.impl;

import com.alibaba.fastjson.JSON;
import com.alipan.constant.Constants;
import com.alipan.response.DriveInfoResponse;
import com.alipan.response.TokenResponse;
import com.alipan.service.HttpClient;
import com.alipan.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    private HttpClient httpClient;

    @Autowired
    public void setHttpClient(HttpClient httpClient) {
        this.httpClient = httpClient;
    }

    @Override
    public TokenResponse accessToken(String clientId, String secret, String grantType, String code) {
        Map params = new HashMap<>();
        params.put("client_id", clientId);
        if (secret.length() >= 64) {
            params.put("code_verifier", secret);
        } else {
            params.put("client_secret", secret);
        }
        params.put("grant_type", grantType);
        if ("authorization_code".equals(grantType)) {
            params.put("code", code);
        } else {
            params.put("refresh_token", code);
        }
        String body = httpClient.post(null, Constants.ACCESS_TOKEN, params);
        return JSON.parseObject(body, TokenResponse.class);
    }

    @Override
    public String spaceInfo(Map<String, String> headers) {
        return httpClient.post(headers, Constants.SPACE_INFO, null);
    }

    @Override
    public DriveInfoResponse driveInfo(Map<String, String> headers) {
        String body = httpClient.post(headers, Constants.DRIVE_INFO, null);
        return JSON.parseObject(body, DriveInfoResponse.class);
    }

    @Override
    public String userInfo(Map<String, String> headers) {
        return httpClient.get(headers, Constants.USERS_INFO);
    }

}
